#include<iostream>
#include"mytcp.hpp"
#include"common.hpp"
#include"protocol.hpp"
#include<string>
#include<memory>
int main(int argc,char* argv[])
{
    //格式:./main port
    if(argc!=3)
    {
        //格式输入错误
        std::cout<<"格式输入错误,应该为:./main ip port"<<std::endl;
        exit(0);
    }
    std::string ip=argv[1];
    uint16_t port=std::stoi(argv[2]);
    std::unique_ptr<Socket> client=std::make_unique<TcpSocket>();
    client->BuildClientMethod();
    std::unique_ptr<Protocol> p=std::make_unique<Protocol>();
    if(client->Connect(ip,port))
    {
        //成功,此时可以向服务器发送消息
        int x=0;
        int y=0;
        char oper=0;
        while(true)
        {
            std::cout<<"请输入x值:";
            cin>>x;
            std::cout<<"请输入y值:";
            cin>>y;
            std::cout<<"请输入运算符:";
            cin>>oper;
            //将值转换为加码的json串
            std::string req_str=p->BuildRequestString(x,y,oper);
            //把请求发给服务器
            cout << "req_str: " << req_str << endl;
            int n=client->Send(req_str);
            std::cout<<"发送消息n="<<n<<std::endl;
            if(n>0)
            {
                std::cout<<"n>0,进入接收态"<<std::endl;
                std::string getresult;
                Response resp;
                //发送成功,检查收到的是否为一个完整的答案
                bool ok=p->IsResponse(client,getresult,&resp);
                std::cout<<ok<<std::endl;
                if(!ok)
                {
                    break;
                }
                //打印答案
                resp.ShowResult();
            }
            else
            {
                //发送失败
                std::cout<<"请求发送失败"<<std::endl;
                continue;
            }
        }
    }
    return 0;
}